<?php
/***************************************************************************
 *
 *   copyright            : (C) 2011 Winds of Storm
 *
 *   $Id: events.php 155 2011-06-20 16:01:58Z stormerider $
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

require_once("config.php");
$skip_header    = 1;    // don't autoload headers on this page...
require_once($libdir . "init." . $phpEx);
require_once($libdir . "chat_functs." . $phpEx);

$sid    = $_REQUEST['sid'];
$sql    = "SELECT room_id,user_id FROM {$dbprefix}sessions WHERE session_id='$sid'";
$result = $db->sql_query($sql);
if ($result) {
    $rows   = $db->sql_numrows($result);
} else {
    $rows   = 0;
}

$baseurl    = getBaseURI();

if ($rows == 0) {
    if ($_REQUEST['cpsp'] == MODE_SLIMCHAT) {
        showFatalError("Session Expired, please log back in.");
    } else {
        print("<script language=javascript src=\"$baseurl/js/chat_functions.js\"></script>\n");
        print("<script>");
        print("\tSTC('Session Expired, please log back in.', 3);\n");
        print("\tsetURL('');\n");
        print("</script>");
    }
    exit;
}

$result = $db->sql_query($sql);
$row    = $db->sql_fetchrow($result);

if ($row['room_id'] == -1) {
    if ($_REQUEST['cpsp'] == MODE_SLIMCHAT) {
        showFatalError("Session Expired, please log back in.");
    } else {
        print("<script language=javascript src=\"$baseurl/js/chat_functions.js\"></script>\n");
        print("<script>");
        print("\tSTC('Session Expired, please log back in.', 3);\n");
        print("\tsetURL('');\n");
        print("</script>");
    }

    $sql    = "DELETE FROM {$dbprefix}sessions WHERE session_id='$sid'";
    $db->sql_query($sql);
    exit;
}

$sql    = "UPDATE {$dbprefix}sessions SET pull_timer=0 WHERE session_id='$sid'";
$db->sql_query($sql);

$mid    = 0;
if (isset($_REQUEST['mid'])) {
    $mid    = $_REQUEST['mid'];
}
$userid = $row['user_id'];

$sql    = "SELECT * FROM {$dbprefix}prefs WHERE user_id=$userid";
$res    = $db->sql_query($sql);
$p_row  = $db->sql_fetchrow($res);

$refresh    = 5;

$sql    = "SELECT * FROM {$dbprefix}ignore WHERE ignoring_user_id=$userid";
$res    = $db->sql_query($sql);
while (($row = $db->sql_fetchrow($res))) {
        $ignore[]       = $row['ignored_user_id'];
}

$isql   = '';
if (isset($ignore) && is_array($ignore)) {
        $isql   = ' AND user_id_from NOT IN (' . join(',', $ignore) . ') ';
}

if ($_REQUEST['cpsp'] == MODE_SLIMCHAT) {
    $limit  = 40;
    $sql    = "SELECT e.*
            FROM
                {$dbprefix}sessions AS s,
                {$dbprefix}events AS e
            WHERE
                s.session_id='$sid' AND
                (
                    s.room_id=e.room_id_to OR
                    s.user_id=e.user_id_to OR
                    e.room_id_to=-1
                ) AND
                event_chat_flags!=4 $isql
            ORDER BY
                event_id DESC
            LIMIT
                $limit";
} else if ($mid <= 0) {
    $limit  = 30;

    $sql    = "SELECT e.*
            FROM
                {$dbprefix}sessions AS s,
                {$dbprefix}events AS e
            WHERE
                s.session_id='$sid' AND
                (
                    s.room_id=e.room_id_to OR
                    s.user_id=e.user_id_to OR
                    e.room_id_to=-1
                ) AND
                event_chat_flags!=4 $isql
            ORDER BY
                event_id DESC
            LIMIT
                $limit";
    addToLog("Initial Client Pull SQL: $sql");
} else {
    $sql    = "SELECT e.*
            FROM
                {$dbprefix}sessions AS s,
                {$dbprefix}events AS e
            WHERE
                s.session_id='$sid' AND
                (
                    s.room_id=e.room_id_to OR
                    s.user_id=e.user_id_to OR
                    e.room_id_to=-1
                ) $isql AND
                e.event_id>$mid
            ORDER BY
                event_id";
}
$result = $db->sql_query($sql);

$count  = 0;
while ($row = $db->sql_fetchrow($result)) {
    $eid    = $row['event_id'];
    $etxt   = $row['event_text'];

    if ($_REQUEST['cpsp'] == MODE_SLIMCHAT) {
        $etxt   = stripslashes($etxt);
        // <span class=user>-allikitten (<i>forever...</i>)-</span>
        $etxt   = eregi_replace("^<span class=user>-([^\(]*) \(<i>(.*)</i>)-</span> ", "-\\1- ", $etxt);
    } else {
        $events[$eid]['EVENT_FLAGS']    = $row['event_chat_flags'];

        if ($eid > $mid) {
            $mid    = $eid;
        }
    }
    $events[$eid]['EVENT_ID']   = $eid;
    $events[$eid]['EVENT_TEXT'] = $etxt;
}

if ($_REQUEST['cpsp'] == MODE_SLIMCHAT) {
    $url    = "events.$phpEx?sid=$sid&cpsp=" . MODE_SLIMCHAT;
    $tpl    = 'events_slim.tpl';
} else {
    $url    = "events.$phpEx?sid=$sid&mid=$mid&cpsp=" . MODE_CLIENT_PULL;
    $tpl    = 'events_body.tpl';
    if (isset($events) && is_array($events))
        ksort($events);
}
$body['class']  = 'row2';
$header         = array();
if ($_REQUEST['cpsp'] != MODE_CLIENT_PULL) {
    $header[]['HEADER_TEXT']    = "<meta http-equiv=refresh content='$refresh; URL=$url'>\n";
}
showHeader($body, $header, array('chat_functions.js'));

if ($_REQUEST['cpsp'] == MODE_CLIENT_PULL) {
    print("URL = $url<br />\n");
    print("MID = $mid<br />\n");
}

$template = new Template($config['TPL_DIR']);
$template->set_filenames(array('body' => $tpl));
$template->assign_vars(array(
    'U_BASEURL' => getBaseURI(),
));

if ($_REQUEST['cpsp'] == MODE_CLIENT_PULL) {
    $onload = "setMID($mid);\n        setURL('events.$phpEx?sid=$sid');";
    $template->assign_block_vars('onload', array(
        'JS'    => $onload,
    ));
}

if ((!isset($_REQUEST['mid']) || $_REQUEST['mid'] <= 0) && $p_row['user_font'] && $_REQUEST['cpsp'] != MODE_SLIMCHAT) {
    $font   = $p_row['user_font'];
    if (ereg(' ', $font)) {
        $font   = '"'.$font.'"';
    }
    $css    = getFontCSS($p_row['user_font'], $p_row['user_size'], false);
    $template->assign_block_vars('css', array(
        'CSS'   => $css,
    ));
}
if ((!isset($_REQUEST['mid']) || $_REQUEST['mid'] <= 0) && $p_row['user_css'] && $_REQUEST['cpsp'] != MODE_SLIMCHAT) {
    $template->assign_block_vars('css', array(
        'CSS'   => $p_row['user_css']
    ));
}

if (isset($events) && is_array($events)) {
    foreach ($events as $thisevent) {
        $template->assign_block_vars('events', $thisevent);
    }
}

$template->pparse('body');
